package com.xinlong.shop.framework.security.filter;

import com.xinlong.shop.framework.core.model.LoginAdmin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.Collection;

/**
 * @Author Sylow
 * @Description
 * @Date: Created in 22:27 2022/5/31
 */
@Component
public class UrlAccessDecisionManager implements AccessDecisionManager {

    private static final Logger logger = LoggerFactory.getLogger(UrlAccessDecisionManager.class);

    @Override
    public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {

        // 判断是否登录
        if (!(authentication instanceof UsernamePasswordAuthenticationToken)) {
            throw new BadCredentialsException("未登录");
        }

        UserDetails userDetails = (UserDetails) authentication.getPrincipal();

        for(ConfigAttribute configAttribute : collection) {

            // 如果是管理员的 判断特殊权限
            if (userDetails instanceof LoginAdmin) {
                if ("ROLE_COMMON".equals(configAttribute.getAttribute())) {
                    // 通用权限通过
                    return;
                }
            }

            // 循环判断权限
            for(GrantedAuthority grantedAuthority : userDetails.getAuthorities()) {

                logger.debug("权限{}，权限{}", configAttribute.getAttribute(), grantedAuthority.getAuthority());
                if (configAttribute.getAttribute().equals(grantedAuthority.getAuthority())) {
                //if(PatternMatchUtils.simpleMatch(configAttribute.getAttribute(),grantedAuthority.getAuthority())) {
                    // 有一个权限就行
                    //logger.debug("找到{}权限", loginUser.getSysUser().getUsername());
                    return;
                }
            }
        }

        throw new AccessDeniedException("权限不足");

    }

    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
